import { CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer.js';
import { CSS3DObject, CSS3DSprite } from 'three/examples/jsm/renderers/CSS3DRenderer.js';

export default class Label {
  constructor(options) {
    this.options = {
      renderer: '3d', // 2d、3d
      faceToCamera: true, // 2d渲染器下只能朝向相机，3d渲染器下可以朝向相机也可以不朝向相机
      scale: 0.05, // 3d渲染器下的缩放
      position: [0, 0, 0],
      html: null,
      ...options,
    };

    return this.#createLabel();
  }

  #createLabel() {
    const { renderer, faceToCamera, scale, html, position } = this.options;

    const label = document.createElement('div');
    label.className = 'three-label';
    label.style.position = 'relative';
    label.style.with = '0';
    label.style.height = '0';
    label.appendChild(html);

    let labelObject;

    if (renderer === '2d') {
      labelObject = new CSS2DObject(label);
    } else if (renderer === '3d') {
      if (faceToCamera) {
        labelObject = new CSS3DSprite(label);
      } else {
        labelObject = new CSS3DObject(label);
      }

      labelObject.scale.set(scale, scale, 1);
    }

    labelObject.position.set(...position);

    return labelObject;
  }
}
